const net = require('net');
const mysql = require('mysql2/promise');
const { type } = require('os');
const moment = require('moment/moment');
const { v4: uuidv4 } = require("uuid");

// 创建数据库连接
const connectDB = async () => {
    const connection = await mysql.createConnection({
        host: '106.52.21.126',
        user: 'root',
        password: '513164001lzs',
        database: 'expresswayCamera',
        port: 3307
    });
    return connection;
};


const startServer = async () => {
    const connection = await connectDB();

    const server = net.createServer(async (socket) => {
        console.log('客户端已连接...');
        socket.on('data', async (data) => {
            try {
                let dataArr = data.toString().split('\n').filter(Boolean);
                let dataObj = {};
                let eventtype, count = -1;
                dataArr.forEach(item => {
                    let arr = item.split('=');
                    let key = arr[0]
                    if (key) {
                        let value = arr[1];
                        if (key == 'info') {
                            dataObj[key] = item;
                            const regex1 = new RegExp('type=' + '(.*?)' + '&', 's');
                            eventtype = item.match(regex1)[1];
                            // 获取计数
                            const regex2 = new RegExp('val=' + '(.*?)' + ']', 's');
                            let countData = item.match(regex2);
                            if (countData) {
                                count = countData[1]
                            }
                        } else if (key == 'datetime') {
                            dataObj[key] = moment(new Date(Date.parse(value))).format('YYYY-MM-DD HH:mm:ss');
                        } else {
                            dataObj[key] = value;
                        }
                    }
                })
                if (eventtype == 'counting' && count != -1) {
                    let message = [uuidv4().replace(/-/g, ""), dataObj.ip, dataObj.datetime, dataObj.unitname, count, dataObj.dts, dataObj.info];
                    // 1、设防中，2、滞留车辆数预警，3、滞留时间预警，4，警报中，5，排查中，6，停止设防
                    let queryData = await connection.execute(
                        'select * from video_partner where enter_camera_ip = ? OR out_camera_ip = ?',
                        [dataObj.ip, dataObj.ip]
                    );
                    let data = queryData[0][0];
                    if (data && ![5, 6].includes(data.status)) {
                        await connection.execute(
                            'INSERT INTO camera_video (id, unitip, datetime, unitname, count, dts, info) VALUES (?, ?, ?, ?, ?, ?, ?)',
                            message
                        );
                        console.log('inserted')
                    }
                }
            } catch (error) {
                console.error('数据库插入错误:', error);
            }
        });

        socket.on('end', () => {
            console.log('客户端已断开连接');
        });
    });

    server.listen(8086, () => {
        console.log('服务器正在监听8086端口');
    })

    // 处理程序退出时关闭数据库连接
    process.on('exit', () => {
        connection.end();
    });
};

startServer().catch(console.error);





















